;+
; NAME:
;       HYP_FLATTEN_IMG
;
; PURPOSE:
;       Take the component-by-component .FITS image output by the
;       HYPERION export_images.py script and combine into a single 2D
;       image file with appropriate .FITS header information.
;
; CATEGORY:
;       HYPERION wrapper
;
; CALLING SEQUENCE:
;       HYP_FLATTEN_IMG, fitsfn
;
; INPUTS:
;       FITSFN -- Filename of the .FITS cube output by the HYPERION
;                 script.
;
; OPTIONAL INPUTS:
;       NONE
;
; KEYWORD PARAMETERS:
;       NONE
;
; OUTPUTS:
;       NONE
;
; OPTIONAL OUTPUTS:
;       NONE
;
; MODIFICATION HISTORY:
;
;       Created:  09/24/12, TPEB -- Initial version
;
;-

PRO HYP_FLATTEN_IMG, fitsfn
  
  ;; Check file existance
  IF ~ FILE_TEST(fitsfn,/READ) THEN BEGIN
     message,'Filename '+fitsfn+' does not exist.  Returning...',/cont
     RETURN
  ENDIF
  
  ;; Read in the FITS cube & measure size
  im = readfits(fitsfn,hd,/silent)
  sz = size(im,/DIM)
  
  ;; Sum all components into totim
  totim = total(im,1)
  sz = size(totim,/DIM)
  
  ;; Create FITS astrometry structure
  make_astr,astr,CRPIX=[sz[0]+0.5,sz[1]/2.+0.5],CRVAL=[0.,0.],$
            CD=[[-0.25d,0.d],[0.d,0.05d]],CTYPE=['GLON-CAR','GLAT-CAR']
  sxaddpar,hd,'NAXIS',2
  sxaddpar,hd,'NAXIS1',sxpar(hd,'NAXIS2')
  sxaddpar,hd,'NAXIS2',sxpar(hd,'NAXIS3')
  sxdelpar,hd,['NAXIS3','NAXIS4']
  putast,hd,astr
  
  ;; Add FITS header keywords and check NAXIS* count
  check_fits,totim,hd,/update
  sxaddpar,hd,'BUNIT','MJy/sr',AFTER='EQUINOX'
  
  ;; Write image + header to file
  writefits,fitsfn,totim,hd
  
  ;; plotmap,totim,hd,ct=3
  
END
